<template>
	<view class="xbc-editor" :class="{border: !fastEntries.length}">
		<!--输入区-->
		<scroll-view class="scroll" scroll-x >
			<view class="item" @tap="selectEntry(item)" v-for="item in fastEntries" :key="item.id">{{ item.name }}</view>
		</scroll-view>
		
		<!--输入区-->
		<view v-show="showTip" class="tip" :style="{top: fastEntries.length ? '15px' : '-50rpx'}">{{ tipText }}</view>
		<view class="top flex-row">
			<view class="icon flex-column">
				<text v-if="conversation.status == XBCCS.CONVERSATION_STATUS.QUEUEING" @tap="cancelQueue" class="iconfont icon-service" style="color: red;"></text>
				<text v-else-if="conversation.staffId" @tap="overAgent" class="iconfont icon-service" style="color: green;"></text>
				<text v-else @tap="toAgent" class="iconfont icon-service"></text>
			</view>
			<view class="block flex-row">
				<textarea
					@linechange="onLinechange"
					@blur="onBlur"
					@focus="onFocus"
					v-model="content"
					class="textarea"
					:style="inputStyle"
					:show-confirm-bar="false"
					:cursor-spacing="24"
					:maxlength="10000"
					:auto-blur="true"
					auto-height
					fixed />
				<view @tap="trigger(oper == 'emoji' ? 'input' : 'emoji')" class="icon flex-column">
					<text class="iconfont icon-smile"></text>
				</view>
			</view>
			<view class="button flex-row">
				<view @tap="trigger(oper == 'more' ? '' : 'more')" v-show="!content" class="icon flex-column">
					<text class="iconfont icon-plus-circle" :style="{transform: oper == 'more' ? 'rotate(45deg)' : 'rotate(0deg)'}"></text>
				</view>
				<view @tap="sendTextMessage" v-show="content" class="send flex-column">发送</view>
			</view>
		</view>
		<!--表情-->
		<xbc-emoji @select="selectEmoji" v-show="oper == 'emoji'" :show="!isFocus" />
		<!--更多-->
		<xbc-more @success="handleMore" v-show="oper == 'more'" :show="!isFocus" />
	</view>
</template>

<script lang="ts" setup>
import { useEditor } from '@/hooks/useEditor'
import { nextTick, ref, watch, computed, onMounted, getCurrentInstance } from 'vue'
import XbcMore from './components/more/index.vue'
import XbcAudio from './components/audio/index.vue'
import XbcEmoji from './components/emoji/index.vue'
import XBCCS from 'xbccs'

const instance = getCurrentInstance()
const { scrollToBottom, getFootHeight } = useEditor(instance)
const emit = defineEmits(['change', 'send', 'fail', 'toAgent', 'overAgent', 'cancelQueue'])
const oper = ref('input')	// 当前操作：input-输入，audio-录音，emoji-表情，more-更多
const content = ref('')
const isFocus = ref(false)
const showTip = ref(true)
const fastEntries = ref([])
const quoteMessage = ref(null)
const mentionMembers = ref([])
const inputLineHeight = ref('64rpx')
const placeholderHeight = ref('92px')
const inputStyle = ref({
	padding: 'initial',
	lineHeight: '64rpx'
})
const props = defineProps({
	conversation: { type: Object, default: () => ({}) },
})
const tipText = computed(() => {
	if(props.conversation.status == XBCCS.CONVERSATION_STATUS.QUEUEING){
		return '取消排队'
	}else if(props.conversation.staffId){
		return '结束人工'
	}else{
		return '转接人工'
	}
})

// 转人工
async function toAgent() {
	await XBCCS.toAgent(props.conversation.conversationId)
	emit('toAgent')
	showTip.value = true
}

// 结束人工
function overAgent() {
	uni.showModal({
		title: '提示',
		content: '是否结束人工？',
		success: res => {
			if(res.cancel) return
			
			XBCCS.overAgent(props.conversation.conversationId).then(() => {
				emit('overAgent')
			})
		}
	})
}

// 取消排队
function cancelQueue() {
	uni.showModal({
		title: '提示',
		content: '是否取消排队？',
		success: res => {
			if(res.cancel) return
			
			XBCCS.cancelConversationQueue(props.conversation.conversationId).then(() => {
				emit('cancelQueue')
			})
		}
	})
}

// 发送文本消息
function sendTextMessage() {
  try {
    // 组合文本消息体
    const message = XBCCS.createTextMessage({
		id: Date.now(),
		conversationId: props.conversation.conversationId,
		content: content.value,
	})
	
	// 抛出事件
	emit('send', {
		...message,
		senderType: XBCCS.SENDER_ROLE.CUSTOMER,
		status: XBCCS.MESSAGE_STATUS.SENDING
	})
	
	// 发送消息
	sendMessage(message)
  } catch (error) {
    console.error(error)
  }
}

// 发送消息
function sendMessage(message: any) {
  XBCCS.sendMessage(message).then(() => {
	  // 上传成功
  }).catch(() => {
	  emit('fail', {
		  ...message,
		  senderType: XBCCS.SENDER_ROLE.CUSTOMER,
		  status: XBCCS.MESSAGE_STATUS.SENDING
	  })
  })
  content.value = ''
  quoteMessage.value = null
}

// 重发消息
XBCCS.on('message-resend', (message: any) => {
	message.status = XBCCS.MESSAGE_STATUS.SENDING
	message.content = typeof message.content === 'string' ? JSON.parse(message.content) : message.content
	sendMessage(message)
})

// 切换
async function trigger(op: string) {
	oper.value = op
	await getFootHeight(placeholderHeight)
	await nextTick()
	await scrollToBottom()
}

// 选择快速入口
function selectEntry({ id, name, type, content: url }){
	// 设置次数
	XBCCS.setEntryTimes(id)
	
	// 文本时；发送消息
	if (type === 'text') {
		content.value = name
		sendTextMessage()
	} else if (type === 'link') {
		// #ifdef APP-PLUS
		plus.runtime.openURL(url)
		// #endif
		 
		// #ifdef H5
		window.location.href = url
		// #endif
		 
		// #ifdef MP-WEIXIN
		uni.navigateTo({
		  url: `/pages/webview?url=${encodeURIComponent(url)}`
		});
		// #endif
	}
}

// 获取快捷入口
async function getEntryList(){
	const res = await XBCCS.getEntryList()
	fastEntries.value = res || []
}

// 处理更多
function handleMore({ type, data }) {
	let message: any
	const { conversationId } = props.conversation
	
	switch (type){
		case 'image':
			message = XBCCS.createImageMessage({
				...data,
				id: data.uid,
				conversationId
			})
			break
		case 'goods':
			message = XBCCS.createGoodsMessage({
				...data,
				id: Date.now(),
				conversationId,
			})
			break
		case 'order':
			message = XBCCS.createOrderMessage({
				...data,
				id: Date.now(),
				conversationId,
			})
			break
	}
	
	// 抛出事件
	emit('send', {
		...message,
		senderType: XBCCS.SENDER_ROLE.CUSTOMER,
		status: XBCCS.MESSAGE_STATUS.SENDING
	})
	
	// 执行发送
	sendMessage(message)
	reset()
}

// 选择表情
function selectEmoji(emoji: string) {
	content.value += emoji
}

// 监听失焦
function onBlur() {
	isFocus.value = false
	getFootHeight(placeholderHeight)
}

// 监听聚焦
function onFocus() {
	isFocus.value = true
	// #ifndef MP-WEIXIN
	oper.value = 'input'
	// #endif
	getFootHeight(placeholderHeight)
}

// 监听输入
function onLinechange(e) {
	if(e.detail.lineCount > 1){
		inputStyle.value.padding = '20rpx 0'
		inputStyle.value.lineHeight = '1.2'
	}else{
		inputStyle.value.padding = 'initial'
		inputStyle.value.lineHeight = '64rpx'
	}
}

// 重置
function reset(isBottom: Boolean = true) {
	oper.value = 'input'
	getFootHeight(placeholderHeight, isBottom)
}

watch(placeholderHeight, height => {
	emit('change', height)
})

watch(showTip, () => {
	if(showTip.value){
		setTimeout(() => {
			showTip.value = false
		}, 2500)
	}
}, { immediate: true })

onMounted(() => {
	getEntryList()
})

defineExpose({
	reset
})
</script>

<style lang="scss" scoped>
.xbc-editor {
	width: 100%;
	background-color: #f5f5f5;
	transition: height 0.3s ease;
	position: fixed;
	bottom: 0;
	left: 0;
	z-index: 99;
	
	::-webkit-scrollbar {
		display: none;
	}
	
	&.border{
		border-top: 2rpx solid #eee;
	}
	
	.scroll{
		width: 100%;
		height: 40px;
		padding-top: 20rpx;
		padding-left: 30rpx;
		white-space: nowrap;
		background-color: #f5f5f5;
		
		.item{
			padding: 0 30rpx;
			font-size: 24rpx;
			margin-right: 30rpx;
			border-radius: 44rpx;
			display: inline-block;
			background-color: #fff;
			@include line-height(28px);
		}
	}
	
	.tip{
		color: #fff;
		line-height: 1;
		font-size: 24rpx;
		padding: 16rpx 20rpx;
		background: rgba(0, 0, 0, 0.7);
		position: absolute;
		left: 0;
		top: -50rpx;
		z-index: 10000;
		
		&::after{
			content: '';
			@include fullsize(0);
			border-left: 12rpx solid transparent;
			border-right: 12rpx solid transparent;
			border-top: 14rpx solid rgba(0, 0, 0, 0.7);
			position: absolute;
			left: 40rpx;
			top: 100%;
		}
	}
	
	.top {
		padding: 20rpx;
		min-height: 52px;
		overflow: hidden;
		align-items: flex-end;
		
		.send {
			color: #fff;
			width: 100rpx;
			height: 64rpx;
			margin: 0 10rpx;
			font-size: 28rpx;
			border-radius: 10rpx;
			background-color: #2BA245;
		}
		
		.block {
			flex: 1;
			margin: 0 20rpx;
			padding: 0 20rpx;
			overflow: hidden;
			min-height: 64rpx;
			border-radius: 10rpx;
			background-color: #fff;
			position: relative;
		}
		
		.textarea {
			color: #333;
			width: 100%;
			font-size: 28rpx;
			min-height: 64rpx;
			line-height: 64rpx;
			max-height: 160px;
			background-color: #fff;
		}
		
		.icon {
			@include fullsize(64rpx);
			
			.iconfont {
				font-size: 60rpx;
				transition: transform 0.2s ease;
				
				&.icon-emoji {
					font-size: 58rpx;
				}
				
				&.icon-smile {
					color: #444;
					font-size: 56rpx;
				}
				
				&.icon-service,
				&.icon-service1,
				&.icon-service2 {
					color: #333;
					font-size: 56rpx;
				}
			}
		}
	}
}

</style>